# from django.contrib.auth.models import AnonymousUser
# from django_redis import get_redis_connection
# from rest_framework.generics import ListCreateAPIView
# from rest_framework.response import Response
# from rest_framework.viewsets import ModelViewSet
#
# from apps.spit.mixins import CommonPagination
# from apps.spit.models import Spit
# from apps.spit.serializer.spit import SpitSerializer
#
#
# class SpitViewSet(ModelViewSet):
#     serializer_class = SpitSerializer
#     queryset = Spit.objects.all()
#     pagination_class = CommonPagination
#
#     # def get_serializer_class(self):
#     #     if self.request.method == 'post':
#     #         if not self.request.user and not self.request.data.get('parent'):
#     #             return Response({'success':'False','message':'发表吐槽需要登录'})
#     #         else:
#     #             return SpitSerializer
#     def list(self, request,*args, **kwargs):
#         queryset = Spit.objects.filter(parent_id__isnull=True)
#         count = queryset.count()
#         ser = self.get_serializer(queryset, many=True)
#         for s in ser.data:
#             s['share']=0
#             s['state']=0
#         return Response({'count': count, 'next': '', 'previous': '', 'results': ser.data})
#
#     def create(self,request,*args, **kwargs):
#         content = self.request.data.get('content')
#         # print(**kwargs)
#         new_spit = Spit()
#         new_spit.content=self.request.data
#         new_spit.save()
#
#         return Response({'success':True})
#
#     def collect(self, request, id):
#         try:
#             user = request.user
#         except Exception:
#             user = None
#         if user is not None and user.is_authenticated:
#             redis_conn = get_redis_connection('spit')
#             flag = redis_conn.hget("spit_collect_%s" % user.id, id)
#             if flag:
#                 redis_conn.hdel('spit_collect_%s' % user.id, id)
#                 return Response({'success': True, 'message': '取消收藏成功'})
#             else:
#                 redis_conn.hset("spit_collect_%s" % user.id, id, 1)
#                 return Response({'success': True, 'message': '收藏成功'})
#         else:
#             return Response({'success': False, 'message': '未登录'}, status=400)
#
#     def updatethumbup(self, request, id):
#         try:
#             user = request.user
#         except Exception:
#             user = None
#         if user is not None and user.is_authenticated:
#             redis_conn = get_redis_connection('spit')
#             flag = redis_conn.hget("spit__updatethumbup%s" % user.id, id)
#             if flag:
#                 redis_conn.hdel('spit_updatethumbup_%s' % user.id, id)
#                 return Response({'success': True, 'message': '取消点赞成功'})
#             else:
#                 redis_conn.hset("spit_updatethumbup_%s" % user.id, id, 1)
#                 return Response({'success': True, 'message': '点赞成功'})
#         else:
#             return Response({'success': False, 'message': '未登录'}, status=400)
#
#     def children(self, request, id):
#         queryset = Spit.objects.filter(parent_id=id)
#         ser = SpitSerializer(queryset, many=True)
#         return Response(ser.data)



# from spit.models import Spit
# from tensquare.apps.spit.models import Spit
# from rest_framework import serializers
from rest_framework import serializers
from rest_framework.exceptions import ValidationError



# class SpitSerializer(serializers.DocumentSerializer):
from apps.spit.models import Spit


class SpitSerializer(serializers.ModelSerializer):

    class Meta:
        model = Spit
        fields = "__all__"

    def create(self, validated_data):
        spit = super().create(validated_data)

        try:
            user = self.context["request"].user
        except:
            user = None

        #    判断是否是评论别人
        if spit.parent:
            # 评论别人必须登陆
            if user and user.is_authenticated:
                spit.userid = str(user.id)
                spit.nickname = user.nickname if user.nickname else user.username
                spit.avatar = user.avatar
                spit.save()
                spit.parent.comment += 1
                spit.parent.save()
                return spit
            else:
                raise ValidationError('未登录')
        else:
            return spit


